package com.way.gesture;

import java.io.File;

import com.way.util.AppUtil;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SelectTaskActivity extends ListActivity {
	public static final int APP_COMMAND = 0;
	public static final int DIAL_COMMAND = 1;
	public static final int MMS_COMMAND = 2;
	private final Integer mTitles[] = { R.string.app_task, R.string.dial_task,
			R.string.mms_task };
	private Gesture mGesture;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);
		AppUtil.transWindows(this,
				getResources().getColor(R.color.material_teal));
		getActionBar().setDisplayHomeAsUpEnabled(true);
		TaskAdapter adapter = new TaskAdapter(this, mTitles);
		setListAdapter(adapter);
		mGesture = getIntent().getParcelableExtra("gesture");
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		switch (position) {
		case APP_COMMAND:
			Intent appIntent = new Intent(this, SelectAppActivity.class);
			if (TextUtils.equals(getIntent().getAction(), "com.way.edit")) {
				appIntent.setAction(getIntent().getAction());
				appIntent.putExtra("task", getIntent().getStringExtra("task"));
				// appIntent.putExtra("edit_guesture", getIntent()
				// .getParcelableExtra("edit_gesture"));
			}
			if (mGesture != null)
				appIntent.putExtra("gesture", mGesture);
			startActivity(appIntent);
			finish();
			break;
		case DIAL_COMMAND:
			Intent dialIntent = new Intent(Intent.ACTION_PICK,
					ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(dialIntent, DIAL_COMMAND);
			break;
		case MMS_COMMAND:
			Intent mmsIntent = new Intent(Intent.ACTION_PICK,
					ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(mmsIntent, MMS_COMMAND);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		Uri contactData = data.getData();
		Cursor c = managedQuery(contactData, null, null, null, null);
		c.moveToFirst();
		String phoneNum = getContactPhone(c);
		if (TextUtils.isEmpty(phoneNum))
			return;

		Log.i("liweiping", phoneNum);
		Intent i = new Intent(SelectTaskActivity.this,
				CreateGestureActivity.class);
		StringBuilder stringBuilder = new StringBuilder();
		switch (requestCode) {
		case DIAL_COMMAND:
			stringBuilder.append(String.valueOf(DIAL_COMMAND));
			break;
		case MMS_COMMAND:
			stringBuilder.append(String.valueOf(MMS_COMMAND));
			break;

		default:
			break;
		}
		stringBuilder.append(",");
		stringBuilder.append(phoneNum);
		Log.i("liweiping", stringBuilder.toString());
		i.putExtra("task", stringBuilder.toString());
		if (TextUtils.equals(getIntent().getAction(), "com.way.edit")) {
			String name = getIntent().getStringExtra("task");
			// Gesture gesture = getIntent().getParcelableExtra("edit_gesture");
			final GestureLibrary store = GestureLibraries.fromFile(new File(
					getFilesDir(), MainActivity.GESTURE_FILE));
			if (store.load()) {
				Gesture gesture = store.getGestures(name).get(0);
				store.removeGesture(name, gesture);
				store.addGesture(stringBuilder.toString(), gesture);
				store.save();
			}
		} else if (mGesture != null) {
			final GestureLibrary store = GestureLibraries.fromFile(new File(
					getFilesDir(), MainActivity.GESTURE_FILE));
			if (store.load()) {
				store.addGesture(stringBuilder.toString(), mGesture);
				store.save();
			}
		} else {
			startActivity(i);
		}
		finish();
	}

	private String getContactPhone(Cursor cursor) {
		int phoneColumn = cursor
				.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		int phoneNum = cursor.getInt(phoneColumn);
		String result = "";
		if (phoneNum > 0) {
			// 获得联系人的ID号
			int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			String contactId = cursor.getString(idColumn);
			// 获得联系人电话的cursor
			Cursor phone = getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
							+ contactId, null, null);
			if (phone.moveToFirst()) {
				for (; !phone.isAfterLast(); phone.moveToNext()) {
					String phoneNumber = phone
							.getString(phone
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					String name = phone
							.getString(phone
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
					result = phoneNumber + "," + name;
					// int phone_type = phone.getInt(phone
					// .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
					// switch (phone_type) {//此处请看下方注释
					// case 2:
					// result = phoneNumber;
					// break;
					//
					// default:
					// break;
					// }
				}
				if (!phone.isClosed()) {
					phone.close();
				}
			}
		}
		return result;
	}

	private class TaskAdapter extends ArrayAdapter<Integer> {

		private final LayoutInflater mInflater;

		public TaskAdapter(Context context, Integer[] objects) {
			super(context, 0, objects);
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.gestures_item, parent,
						false);
			}
			int title = mTitles[position];
			final TextView label = (TextView) convertView;

			label.setTag(title);
			label.setText(title);
			return convertView;
		}
	}
}
